/* 
 * AndFollowerStat
 * 
 * Copyright (C) 2009  Daniel Czerwonk <d.czerwonk@googlemail.com>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.dan_nrw.android.followerstat.client.followers;

import java.util.concurrent.Semaphore;

import de.dan_nrw.android.followerstat.AsyncTaskResult;
import de.dan_nrw.android.followerstat.DependencyInjector;
import de.dan_nrw.android.followerstat.Follower;
import de.dan_nrw.android.followerstat.R;
import de.dan_nrw.android.followerstat.dao.configuration.IConfigDAO;
import de.dan_nrw.android.followerstat.dao.folllowers.ITwitterFollowerDAO;
import de.dan_nrw.android.followerstat.dao.folllowers.TwitterRequestException;
import de.dan_nrw.android.followerstat.dao.folllowers.TwitterResponseParsingException;
import de.dan_nrw.android.followerstat.dao.folllowers.TwitterUserAccountNotFoundException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;


/**
 * @author Daniel Czerwonk
 *
 */
public class FollowerListActivity extends Activity {

	private final ITwitterFollowerDAO followerDAO;
	private final IConfigDAO configDAO;
	private static FollowerListAdapter followerListAdapter;
	private static final Semaphore semaphore = new Semaphore(1);
	
	
    /**
     * Creates a new instance of FollowerListActivity.
     */
    public FollowerListActivity() {
	    super();
	    
	    this.configDAO = DependencyInjector.getInstance(IConfigDAO.class);
	    this.followerDAO = DependencyInjector.getInstance(ITwitterFollowerDAO.class);
    }

    
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
    protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    this.setTitle(String.format("%s: %s", 
	    							this.getString(R.string.applicationName), 
	    							this.getString(R.string.followersText)));
	    
	    this.setContentView(R.layout.followers);
	    
	    if (followerListAdapter != null) {
	    	ListView listView = (ListView)this.findViewById(R.id.followersListView);
        	listView.setAdapter(followerListAdapter);
	    	
	    	return;
	    }
	    
    	AsyncTask<Object, Integer, AsyncTaskResult<Follower[]>> task = new ShowFollowerListTask(this.followerDAO, 
																								this.configDAO.getTwitterUserName(), 
																								this);

    	task.execute();
    }
    
	/* (non-Javadoc)
     * @see android.app.Activity#finish()
     */
    @Override
    public void finish() {    	
    	followerListAdapter = null;
    	
    	super.finish();
    }

	private static void showMessage(Context context, int titleRes, int messageRes, int iconRes) {
		new AlertDialog.Builder(context).setMessage(messageRes)
										.setTitle(titleRes)
										.setIcon(iconRes)
										.setPositiveButton(R.string.okButtonText, null)
										.create()
										.show();
	}
	
    
    private static class ShowFollowerListTask extends AsyncTask<Object, Integer, AsyncTaskResult<Follower[]>> {
    	
    	private final Activity activity;
    	private final ITwitterFollowerDAO followerDAO;
    	private final String userName;
    	private final ProgressDialog progressDialog;
    	
		/**
		 * Method for creating a new instance of UpdateFollowerListTask
		 * @param followerDAO
		 * @param userName
		 * @param activity
		 */
		public ShowFollowerListTask(ITwitterFollowerDAO followerDAO, String userName, Activity activity) {
	        super();
	        
	        this.followerDAO = followerDAO;
	        this.userName = userName;
	        this.activity = activity;
	        
	        this.progressDialog = new ProgressDialog(this.activity);
	        
	        this.progressDialog.setMessage(this.activity.getString(R.string.loadingFollowersText));
	        this.progressDialog.setOnCancelListener(new OnCancelListener() {

				@Override
                public void onCancel(DialogInterface dialog) {
					cancel(true);
                }
	        });
        }

		/* (non-Javadoc)
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected AsyncTaskResult<Follower[]> doInBackground(Object... params) {
        	semaphore.acquireUninterruptibly();
        	
        	AsyncTaskResult<Follower[]> result = new AsyncTaskResult<Follower[]>();
        	
        	try {
	            result.setResult(this.followerDAO.getFollowers(this.userName));
            }
            catch (Throwable ex) {
	            result.setException(ex);
            }
            
            return result;
        }

		/* (non-Javadoc)
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
	        this.progressDialog.show();
        }
        
		/* (non-Javadoc)
         * @see android.os.AsyncTask#onCancelled()
         */
        @Override
        protected void onCancelled() {
        	semaphore.release();
        	
	        this.progressDialog.dismiss();
	        
	        this.activity.finish();
        }

		/* (non-Javadoc)
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(AsyncTaskResult<Follower[]> result) {
        	try {
    	        if (result.getException() != null) {
    	        	this.handleException(result.getException());
    	        }
    	        else {
    	        	followerListAdapter = new FollowerListAdapter(this.activity, result.getResult(), followerDAO);
    	        	
    	        	ListView listView = (ListView)this.activity.findViewById(R.id.followersListView);
    	        	listView.setAdapter(followerListAdapter);
    	        }
        	}
        	finally {
        		semaphore.release();
        		
        		this.progressDialog.dismiss();
        	}
        }
        
        private void handleException(Throwable ex) {
        	if (ex instanceof TwitterUserAccountNotFoundException) {
        		showMessage(this.activity, R.string.errorText, R.string.invalidUsernameErrorText, android.R.drawable.ic_dialog_alert);
        		
        		return;
        	}
        	else if (ex instanceof TwitterResponseParsingException) {
        		showMessage(this.activity, R.string.errorText, R.string.followersRequestParsingErrorText, android.R.drawable.ic_dialog_alert);
        		
        		return;
        	}
        	else if (ex instanceof TwitterRequestException) {
        		showMessage(this.activity, R.string.errorText, R.string.followersRequestErrorText, android.R.drawable.ic_dialog_alert);
        		
        		return;
        	}
        	
        	throw new RuntimeException(ex);
        }
    }
}